<template>
  <div>
    <label for>{{label}}:</label>
    <slot></slot>
    <p v-if="errStatus" class="tip">{{errMessage}}</p>
  </div>
</template>

<script>
import Schema from "async-validator";
export default {
  props: ["label", "prop"],
  inject: ["MyForm"],
  data() {
    return {
      errStatus: false,
      errMessage: ""
    };
  },
  mounted() {
    this.$on("validator", this.validator); //监听子组件传过来的事件
    if(this.prop){
        this.$parent.$emit("formItemAdd",this)
    }
  },
  methods: {
    validator() {
      return new Promise((resolve, reject) => {
        const rule = this.MyForm.rules[this.prop];
        const value = this.MyForm.model[this.prop];

        const schema = new Schema({ [this.prop]: rule });
        schema.validate({ [this.prop]: value }, errors => {
          if (errors) {
            this.errMessage = errors[0].message;
            this.errStatus = true;
            resolve(false)//校验失败
          } else {
            this.errStatus = false;
            this.errMessage = "";
            resolve(true)//校验成功
          }
        });
      });
    }
  }
};
</script>
<style scoped>
.tip {
  color: red;
}
</style>

